package com.edu.web.controller.info;

import cn.hutool.core.util.StrUtil;
import com.edu.common.exception.ServiceException;
import com.edu.framework.websocket.service.BaseInfoService;
import com.edu.framework.websocket.service.TerminalService;

import com.edu.system.domain.dto.EditTerminalDTO;
import com.edu.system.domain.req.UpdateApkReq;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.CollectionUtils;
import org.hibernate.validator.constraints.Range;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.edu.common.annotation.Log;
import com.edu.common.core.controller.BaseController;
import com.edu.common.core.domain.AjaxResult;
import com.edu.common.enums.BusinessType;
import com.edu.system.domain.TTerminal;
import com.edu.system.service.ITTerminalService;
import com.edu.common.utils.poi.ExcelUtil;
import com.edu.common.core.page.TableDataInfo;

/**
 * 机器管理Controller
 *
 * @author xxxx
 * @date 2023-12-21
 */
@RestController
@RequestMapping("/system/terminal")
public class TTerminalController extends BaseController {
    @Autowired
    private ITTerminalService tTerminalService;

    @Autowired
    private TerminalService pushService;
    @Resource
    private BaseInfoService wsBaseInfoService;

    /**
     * 查询机器管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTerminal tTerminal) {
        startPage();
        List<TTerminal> list = tTerminalService.selectTTerminalList(tTerminal);
        return getDataTable(list);
    }

    /**
     * 导出机器管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:export')")
    @Log(title = "机器管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TTerminal tTerminal) {
        List<TTerminal> list = tTerminalService.selectTTerminalList(tTerminal);
        ExcelUtil<TTerminal> util = new ExcelUtil<TTerminal>(TTerminal.class);
        util.exportExcel(response, list, "机器管理数据");
    }

    /**
     * 获取机器管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tTerminalService.selectTTerminalById(id));
    }

    /**
     * 开机/关机
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:onOff')")
    @GetMapping(value = "/onOff/{ids}/{status}")
    public AjaxResult onOff(@PathVariable("ids") Long[] ids, @PathVariable("status") Integer status) {

        return success();
    }

    /**
     * 新增机器管理
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:add')")
    @Log(title = "机器管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTerminal tTerminal) {
        tTerminalService.insertTTerminal(tTerminal);
        if (StrUtil.isNotBlank(tTerminal.getFromTo())){
            pushService.scheduleShutDown(new Long[]{tTerminal.getId()});
        }
        return toAjax(1);
    }

    /**
     * 修改机器管理
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:edit')")
    @Log(title = "机器管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTerminal tTerminal) {
        int i = tTerminalService.updateTTerminal(tTerminal);
        if (StrUtil.isNotBlank(tTerminal.getFromTo())){
            pushService.scheduleShutDown(new Long[]{tTerminal.getId()});
        }
        wsBaseInfoService.pushInfo(tTerminal.getLocationId(), tTerminal.getType());
        return toAjax(i);
    }

    /**
     * 批量修改机器管理
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:edit')")
    @Log(title = "机器管理", businessType = BusinessType.UPDATE)
    @PostMapping("/batchEdit")
    public AjaxResult batchEdit(@RequestBody EditTerminalDTO req) {

        if (CollectionUtils.isEmpty(req.getIds())){
            throw new ServiceException("ids不能为空，请选择机器");
        }
        req.getIds().forEach(id -> {
            TTerminal terminal = new TTerminal();
            terminal.setId(id);
            terminal.setFromTo(req.getFromTo());
            tTerminalService.updateTTerminal(terminal);
        });
        if (StrUtil.isNotBlank(req.getFromTo())){
            pushService.scheduleShutDown(req.getIds().toArray(new Long[0]));
        }

        return toAjax(req.getIds().size());
    }


    /**
     * 删除机器管理
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:remove')")
    @Log(title = "机器管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        // 查机器
        List<String> codes = tTerminalService.selectTTerminalListByIds(ids)
            .stream()
            .map(TTerminal::getCode)
            .collect(Collectors.toList());
        int i = tTerminalService.deleteTTerminalByIds(ids);

        wsBaseInfoService.pushDelete(codes);
        return toAjax(i);
    }


    /**
     * 调整机器音量
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:edit')")
    @PostMapping("/adjustVolume")
    public AjaxResult adjustVolume(@RequestParam Long[] ids, @Range(min = 0,max = 100,message = "level 不在0-100之间") @RequestParam Integer level) {
        return success(pushService.adjustVolume(ids,level));
    }

    /**
     * 关机
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:edit')")
    @PostMapping("/shutDown")
    public AjaxResult shutDown(@RequestParam Long[] ids) {
        return success(pushService.shutDown(ids));
    }

    /**
     * 设置定时开关机
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:edit')")
    @PostMapping("/scheduleShutDown")
    public AjaxResult scheduleShutDown(@RequestParam Long[] ids) {
        return success(pushService.scheduleShutDown(ids));
    }

    /**
     * 更新包
     */
    @PreAuthorize("@ss.hasPermi('system:terminal:edit')")
    @PostMapping("/update/apk")
    public AjaxResult updateAPK(@RequestBody UpdateApkReq req) {

//        http://8.130.163.143/prod-api/profile/upload/2024/02/07/a_20240207231659A003.apk
        if (StrUtil.startWith(req.getVersionNo(), "9")){
            req.setUrl("http://8.130.163.143/prod-api/profile/upload/2024/02/07/a_20240207231659A003.apk");
        }
        return success(pushService.updateAPK(req));
    }

}
